let logger = require("pomelo-logger").getLogger(__filename);

const MAIL_DATA_COLLECTION_NAME = "mailDatas";

let MailDataDao = function (app) {
    this.app = app;
};


MailDataDao.prototype.insert = function (document, callback) {
    let dbClient = this.app.get("gameDBClient");
    dbClient.collection(MAIL_DATA_COLLECTION_NAME, function (error, collection) {
        if (!!error) {
            logger.error("insert mailData failed. error=" + error);
            callback(null);
            return;
        }
        collection.insert(document, function (error, document) {
            if (!!error) {
                logger.error("insert mailData failed. error=" + error);
                callback(null);
                return;
            }
            let id = !!document.ops ? document.ops[0]._id : document[0]._id;
            callback(id);
        });
    });
};

MailDataDao.prototype.load = function (ts, callback) {
    let dbClient = this.app.get("gameDBClient");
    dbClient.collection(MAIL_DATA_COLLECTION_NAME, function (error, collection) {
        if (!!error) {
            logger.error("load mail failed. error=" + error);
            callback([]);
            return;
        }
        collection.find({time : {$gt : ts}}).toArray(function (error, document) {
            if (!!error) {
                logger.error("load mail failed. error=" + error);
                callback([]);
                return;
            }
            callback(document);
        });
    });
};

MailDataDao.prototype.getNextMailId = function (callback) {
    let dbClient = this.app.get("gameDBClient");
    dbClient.collection(MAIL_DATA_COLLECTION_NAME, function (error, collection) {
        if (!!error) {
            logger.error("load mail failed. error=" + error);
            callback(null);
            return;
        }
        collection.findOne({}, {sort:{id : -1}, limit: 1}, function (error, document){
            if (!!error) {
                logger.error("load mail failed. error=" + error);
                callback(null);
                return;
            }
            !!document ? callback(document.id) : callback(null);
        });
    });
};

module.exports.create = function (app) {
    return new MailDataDao(app);
};
